import { createWebHashHistory, createRouter,RouteRecordRaw } from 'vue-router'
import { App } from 'vue'
import *  as testModule from './test'

function appendItems<T>(items:Array<T>,item:any){
  let arr;
  if(item){
    arr = Array.isArray(item) ? item : [item];
    items.push(...arr);
  }
  return arr;
}
function appendRoutes(appendToRoot:boolean, rootRoutes:RouteRecordRaw[], map:Record<string,RouteRecordRaw>,routes: RouteRecordRaw[],append:boolean, parentPath:string="@"){
  if(routes && routes.length > 0){
    routes.forEach(route => {
      let key:string=route.path;
      let isRoot = parentPath === "@" || parentPath === "";
      if(isRoot){
        if(appendToRoot){
          rootRoutes.push(route)
        }
      }else if(parentPath){
        let prefix = parentPath.endsWith("/") ? parentPath.substring(0,parentPath.length-1) : parentPath;
        key = `${prefix}/${key||'@'}`
      }

      map[key] = route;

      if(!isRoot && append && parentPath){
        let parent = map[parentPath];
        if(parent){
          parent.children = parent.children || [];
          parent.children.push(route);
        }
      }
      
      if(route.children){
        appendRoutes(false,rootRoutes,map, route.children,false,key)
      }
    })
  }
  return map;
}

function appendModule(data:{
  beforeEach:any[],
  afterEach:any[],
  beforeResolve:any[],
  init:any[],
  route:any[],
},module:any,name:string){
  appendItems(data.beforeEach,module.beforeEach);
  appendItems(data.afterEach,module.afterEach);
  appendItems(data.beforeResolve,module.beforeResolve);
  appendItems(data.init,module.init);
  let subRoutes = appendItems(data.route,module.route);
  if(subRoutes){
    subRoutes.forEach(item=>{
      item.parentPath = item.parentPath ?? name;
    })
  }

  console.log("module:"+name,module)
}
function loadChildren(routes: RouteRecordRaw[]) {

  const data:{
    beforeEach:any[],
    afterEach:any[],
    beforeResolve:any[],
    init:any[],
    route:any[],
  } = {
    beforeEach:[],
    afterEach:[],
    beforeResolve:[],
    init:[],
    route:[]
  };


  const modules = import.meta.glob('./modules/*.ts',{ eager: true })
  const reg = /\.\/modules\/(.*)\.ts/

  

  for(let key in modules){
    let m = reg.exec(key);
    if(m){
      let name = m[1];
      const module:any = modules[key]
      appendModule(data,module,name);
    }
  }

  if(import.meta.env.DEV){
    appendModule(data,testModule,"test");
  }

  let routeMap:Record<string,RouteRecordRaw> = {};
  appendRoutes(false,routes,routeMap,routes,false)
  let subRoutes = data.route;
  while(subRoutes.length > 0){
    let oldCount = subRoutes.length;
    for(let i=subRoutes.length-1;i>=0;i--){
      let item = subRoutes[i];
      const parent = routeMap[item.parentPath];
      appendRoutes(true,routes, routeMap,item.routes,true,item.parentPath);
      if(parent){
        subRoutes.splice(i,1);
      }
    }
    if(oldCount === subRoutes.length){
      console.log("无变化，丢弃剩余配置",subRoutes)
      break;
    }
  }

  console.log("routeMap",routeMap)
 
  return data;
}


const routes = [
  { path: '/', component: () => import('@/layout/DefaultLayout.vue') },
  { path: '/about', component: () => import('@/pages/about.vue') },
]

let data = loadChildren(routes);

console.log("-routes-",routes)
const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

if(data.init.length > 0){
  router.beforeEach(async (to,from)=>{
    for(let fn of data.init){
      let rs = await fn(to,from);
      if(rs){
        return rs;
      }
    }
  })
}
router.beforeEach(async (to, from) => {
  console.log("-----1111-----")
})

if(data.beforeEach.length > 0){
  for(let fn of data.beforeEach){
    router.beforeEach(fn)
  }
}

if(data.beforeResolve.length > 0){
  for(let fn of data.beforeResolve){
    router.beforeResolve(fn)
  }
}

if(data.afterEach.length > 0){
  for(let fn of data.afterEach){
    router.afterEach(fn)
  }
}


export function setupRouter(app:App) {
    app.use(router)
}